package forum.controller;

import forum.DBConnectie;
import forum.Variable;
import forum.wrapper.WrapRequest;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Ivan
 * Date: 2010-7-8
 * Time: 16:41:55
 */

public class DispatcherFilter implements Filter {
	
	static Logger logger;
	
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

    	try {
			String url = ((HttpServletRequest)request).getRequestURI();

            String sub_url = url.substring(url.lastIndexOf("/") + 1);
            if(sub_url.contains("?")){
            	sub_url = url.substring(0,sub_url.lastIndexOf("?"));
            }
			
			WrapRequest req = new WrapRequest((HttpServletRequest)request);
			
			String to = "";

			if(sub_url.endsWith("jsp") || sub_url.endsWith("/") || sub_url.trim().equals("")){
				System.out.println("dochain");
				chain.doFilter(request, response);
			}else if(sub_url.charAt(0) < 'A' || sub_url.charAt(0) > 'Z'){
				chain.doFilter(request, response);
			}else if(sub_url.split("\\.").length==2){
                String[] temp = sub_url.split("\\.");
                String cls = "forum.service." + temp[0];
                Class obj = Class.forName(cls);
                
                logger = Logger.getLogger(obj.getName());
                
                logger.info("Start Invoke Class " + obj.getName() + "'s method :" + temp[1]);
                to = (String) obj.getDeclaredMethod(temp[1],WrapRequest.class).invoke(obj.newInstance(),req);
                logger.info("Success Invoke Class " + obj.getName() + "'s method :" + temp[1]);
                ((HttpServletRequest)request).getRequestDispatcher(Variable.getForumPath() + to).forward(request, response);
            }else{
            	chain.doFilter(request, response);
            }
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			chain.doFilter(request, response);
		}catch (Exception e) {
			e.printStackTrace();
	    }

    }

    public void init(FilterConfig config) throws ServletException {

    }
}
